/**
 * @method request
 * @description 封装基于fetch请求的request方法
 * @param {String} url 请求地址
 * @param {Object}} options 请求的header，请求方式、参数等
 * @param {Bealoon} isLoading 默认false/undefined，不启用loading效果。
 * @param {Bealoon} errorCatch 默认false/undefined,自动catch错误，如果想自己catch错误信息，处理错误信息，请传true
 * @param {Array} errorCode 默认undefined, 系统默认执行ERROR_CODE中的行为方式，要禁止系统弹窗，请传[] 空数组
 * @param {Array} successCode 默认undefined, 系统默认执行SUCCESS_CODE中的行为方式，要禁止系统弹窗，请传[] 空数组
 * @param {Array} warningCode 默认undefined, 系统默认执行WARNING_CODE中的行为方式，要禁止系统弹窗，请传[] 空数组
 *
 */

import * as event from './event/componentEvent';
import storage from '../utils/storage';
import handleCode from '../utils/handleCode';
import { ERROR_CODE, SUCCESS_CODE, WARNING_CODE } from './constant';

require('es6-promise').polyfill();
require('isomorphic-fetch');

// getApiUrl
function getApiUrl(url) {
  return `${url}`;
}

export default function request(
  url,
  { ...options },
  { isLoading, errorCatch, errorCode, successCode, warningCode, content }
) {
  if (isLoading && !window.__POWERED_BY_QIANKUN__) {
    event && event.eventEmitter.emit(event.SHOW_LOADING, content);
    window.top.componentEvent && window.top.componentEvent.eventEmitter.emit(event.SHOW_LOADING, content);
  }
  const p = Promise.race([
    fetch(getApiUrl(url), { ...options, credentials: 'same-origin' }).then((response) => {
      const contentType = response.headers.get('content-type');
      // httpCode 返回200，进入具体业务
      if (response.status === 200) {
        if (contentType && contentType.indexOf('json') !== -1) {
          return response.json().then((json) => {
            // 验证不通过，跳回登录
            if (json.code === 300003) {
              window.top.location.href = process.env.PUBLIC_URL + '/login' || '/login';
              storage.clear();
            }
            if (isLoading && !window.__POWERED_BY_QIANKUN__) {
              event && event.eventEmitter.emit(event.HIDE_LOADING);
            }
            const codes = {
              ERROR_CODE: errorCode ? errorCode : ERROR_CODE,
              SUCCESS_CODE: successCode ? successCode : SUCCESS_CODE,
              WARNING_CODE: warningCode ? warningCode : WARNING_CODE,
            };
            return handleCode(json, codes); // 统一处理code
          });
        } else {
          return response.text().then((text) => {
            if (isLoading && !window.__POWERED_BY_QIANKUN__) {
              event && event.eventEmitter.emit(event.HIDE_LOADING);
            }
            return text;
          });
        }
        // httpCode 为其他状态，如500，
      } else {
        if (isLoading && !window.__POWERED_BY_QIANKUN__) {
          event && event.eventEmitter.emit(event.HIDE_LOADING);
        }
        if (contentType && contentType.indexOf('json') !== -1) {
          return response.json().then((r) => {
            // 交由用户自行处理
            if (errorCatch) {
              return Promise.reject(r);
              //  统一处理error弹窗
            } else {
              if (event) {
                event.eventEmitter.emit(event.SHOW_ERROR_MSG, r.msg);
              } else {
                window.top.componentEvent && window.top.componentEvent.eventEmitter.emit(event.SHOW_ERROR_MSG, r.msg);
              }
              return;
            }
          });
        } else {
          return response.text().then((r) => {
            // 交由用户自行处理
            if (errorCatch) {
              return Promise.reject(r);
              //  统一处理error弹窗
            } else {
              event.eventEmitter.emit(event.SHOW_ERROR_MSG, r.msg);
              window.top.componentEvent && window.top.componentEvent.eventEmitter.emit(event.SHOW_ERROR_MSG, r.msg);
              console.log('统一处理', r);
              return;
            }
          });
        }
      }
    }),
    new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({ code: 111, msg: '请求超时' });
      }, 30 * 1000);
    }),
  ]).catch((res) => {
    console.log(res);
  });
  return p;
}
